<?php

namespace application\Comm;

use library\Core\Config;
use application\comm\Request;
class Func
{
	/**
	 * 格式化输出观察变量
	 * @param type $msg
	 * @return string and array,obj
	 */
	public static function pre($msg){
		echo "<pre>";
		print_r($msg);
		exit();
	}
	
	public static function indexProductUrl($route, $params=[]){
		$default = [
		
				'style_id' => 0,
				'function_id' => 0,
				'price_id' => 0,
				'tag_id' => 0,
				'acreage_id'=>0,
				'p' => 1,
				];
		
		$params = array_merge($default, $params);
		
		return self::createUrl($route,$params);
	}

	/**
	 * 判断路由
	 * @param type $route
	 * @param type $params
	 * @param type $ampersand
	 * @return string
	 */
	public static function ifurl(){
		$r = Request::get('r');
		
		if (!empty($r)){
			
			$url = explode(' ', $r);
			$url1 = explode('/', $url[0]);
			
			if ($url1[0]=='site'){
				switch ($url1[1]){
					case 'index':
						return 1;
						break;
					case 'stores' :
						return 2;
						break;
					case 'flow' :
						return 3;
						break;
					case 'brand' :
						return 4;
						break;
					case 'relation' :
						return 7;
						break;
					}
					
			} else if ($url1[0] == 'house'){
						return 5;
				
				
			} else if ($url1[0] == 'showhome'){
				return 6;
			}else{
				return 1;
			}
		}else{
			return 1;
		}
		
	}
	
    /**
     * 创建路由
     * @param type $route
     * @param type $params
     * @param type $ampersand
     * @return string
     */
    public static function createUrl($route, $params = [])
    {
        $host = Config::getParamsVal('HOST');

        if ($route === '') {
            $route = 'site/index';
        }
        if (strpos($route, '/') === false) {
            $route = strtolower($route) . '/index';
        }
        $route_ori = $route;

        //产品列表生成伪静态链接
        if ($route_ori == 'product/index') {
            //空间分类

            if (isset($params['space'])) {
                $route = $params['space'] ? 'product/' . $params['space'] : 'product/index';
                unset($params['space']);
            }
            //风格
            if (isset($params['style_id'])) {
                $route .= '-s' . $params['style_id'];
                unset($params['style_id']);
            }
            //功能
            if (isset($params['function_id'])) {
                $route .= '-f' . $params['function_id'];
                unset($params['function_id']);
            }
            //价格区间
            if (isset($params['price_id'])) {
                $route .= '-j' . $params['price_id'];
                unset($params['price_id']);
            }
            //产品标签
            if (isset($params['tag_id'])) {
                $route .= '-t' . $params['tag_id'];
                unset($params['tag_id']);
            }
            //面积标签
            if (isset($params['acreage_id'])) {
            	$route .= '-a' . $params['acreage_id'];
            	unset($params['acreage_id']);
            }
            //分页
            if (isset($params['p'])) {
                $route .= '-p' . $params['p'];
                unset($params['p']);
            }
            //排序
            if (isset($params['orderby'])) {
                $route .= '-o' . $params['orderby'];
                unset($params['orderby']);
            }
            if (isset($params['ordertype'])) {
                $route .= '-' . $params['ordertype'];
                unset($params['ordertype']);
            }
        }

        //产品详情生成伪静态链接
        if ($route_ori == 'product/view') {
            $route = 'product/detail-' . $params['id'];
            unset($params['id']);
        }

        //帮助详情生成伪静态链接
        if ($route_ori == 'help/view') {
            $route = 'help/view-' . $params['id'];
            unset($params['id']);
        }

        //装修频道
        if ($route_ori == 'decorate/list') {
            $route = isset($params['cid'])?'decorate/list-' . $params['cid']:'decorate/list';
            unset($params['cid']);
            //分页
            if (isset($params['p'])) {
                $route .= '-p' . $params['p'];
                unset($params['p']);
            }
        }

        if ($route_ori == 'decorate/tag') {
            $route = isset($params['tid'])?'decorate/tag-' . $params['tid']:'decorate/tag';
            unset($params['tid']);
            //分页
            if (isset($params['p'])) {
                $route .= '-p' . $params['p'];
                unset($params['p']);
            }
        }

        if ($route_ori == 'decorate/view') {
            $route = 'decorate/detail-' . $params['id'];
            unset($params['id']);
        }
        
        if ($route_ori == 'showhome/view') {
        	$route = 'showhome/view-' . $params['id'];
        	unset($params['id']);
        }

        //错误页面
        if ($route_ori == 'site/error') {
            $route = 'error';
        }

        if ($route_ori == 'site/brand') {
            $route = 'brand';
        }
        if ($route_ori == 'site/index') {
        	$route = 'index';
        }

        if ($route_ori == 'site/flow') {
            $route = 'flow';
        }
       

        if ($route_ori == 'site/apply') {
            $route = 'apply';
        }
        if ($route_ori == 'site/stores') {
        	$route = 'stores';
        }
        if ($route_ori == 'site/qixing') {
        	$route = 'qixing';
        }

        //全屋列表生成伪静态链接
        if ($route_ori == 'house/index') {

            if (isset($params['type_id'])) {
                $route .= '-t' . $params['type_id'];
                unset($params['type_id']);
            }
            if (isset($params['style_id'])) {
            	$route .= '-s' . $params['style_id'];
            	unset($params['style_id']);
            }
            if (isset($params['acreage_id'])) {
            	$route .= '-a' . $params['acreage_id'];
            	unset($params['acreage_id']);
            }
            //分页
            if (isset($params['p'])) {
                $route .= '-p' . $params['p'];
                unset($params['p']);
            }
            //排序
            if (isset($params['orderby'])) {
                $route .= '-o' . $params['orderby'];
                unset($params['orderby']);
            }
            if (isset($params['ordertype'])) {
                $route .= '-' . $params['ordertype'];
                unset($params['ordertype']);
            }
        }

        $route .= '.html';
        $index = 0;
        foreach ($params as $parmeName => $paramValue) {
            $ampersand = $index ? '&' : '?';
            $route .= $ampersand . $parmeName . '=' . $paramValue;
            $index++;
        }
        return htmlspecialchars($host . $route);
    }

    /**
     * 过滤XSS注入
     */
    public static function filter($dataProvider = [])
    {
        $result = [];
        foreach ($dataProvider as $key => $value) {
            $result[$key] = htmlspecialchars(addslashes($value));
        }
        return $result;
    }

    /**
     * CURL提交请求
     * @param url 要提交的地址
     * @param data 要提交的json数据
     */
    public static function https_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        //curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    /**
     * 获取错误信息
     * @param array $errors
     * @param mix $key
     */
    public static function errors($errors = [], $key = '')
    {
        return isset($errors[$key]) ? $errors[$key] : null;
    }

    /**
     * 成功提醒跳转信息提示
     * @param array $msg
     * @param array $url
     */
    public static function flash_success($msg, $url)
    {
        Cookie::set('success_message', json_encode($msg), 500);
        $route = isset($url[0]) ? $url[0] : '';
        $url = self::createUrl($route, array_splice($url, 1));
        header('Location: ' . $url, true, 302);
        exit();
    }

    /**
     * 错误提醒跳转信息提示
     * @param array $msg
     * @param array $url
     */
    public static function flash_errors($msg = '', $url = '')
    {
        Cookie::set('errors_message', json_encode($msg), 500);
        $route = isset($url[0]) ? $url[0] : '';
        $url = self::createUrl($route, array_splice($url, 1));
        header('Location: ' . $url, true, 302);
        exit();
    }

    /**
     * 格式化时间
     * @param string $format
     * @param int $timestamp
     */
    public static function formatDateTime($format = 'Y-m-d H:i:s', $timestamp = 0)
    {
        if (!$timestamp) {
            return false;
        }
        return date($format, $timestamp);
    }

    public static function getImageCdnRand()
    {
        $img_host = Config::getParamsVal('IMG_HOST');
        $img_path_key = array_rand($img_host, 1);
        return $img_path = $img_host[$img_path_key];
    }

    public static function alert($msg)
    {
        header('Content-type: text/html; charset=UTF-8');
        echo json_encode(array('error' => 1, 'message' => $msg));
        exit;
    }

    /**
     * @param $src
     * @return string
     * 切图JS，css CDN链接
     */
    public static function staticUrl($src)
    {
        $public = Config::getParamsVal('STATIC_HOST');
        
        return $public.$src;
    }

    /**
     * @param $src
     * @return string
     * 上传图片CDN链接
     */
    public static function imgUrl($src)
    {
        $cdn_url = self::getImageCdnRand();
        return $cdn_url . $src;
    }

    /**
     * @param array $param
     * @param array $unsetParam
     * @return string
     * 产品列表链接生成
     */
    public static function productUrl($param = [], $unsetParam = [])
    {
        $default = [

            'style_id' => 0,
            'function_id' => 0,
            'price_id' => 0,
            'tag_id' => 0,
        	'acreage_id'=>0,
            'p' => 1,

        ];

        $params = array_merge($default, Request::getParams());
      
        if ($params['space'] == 'index') $params['space'] = 'keting';
        if (!empty($param)) {
            foreach ($param as $k => $v) {
                $params[$k] = $v;
            }
        }
        if (!empty($unsetParam)) {
            foreach ($unsetParam as $k => $v) {
                unset($params[$v]);
            }
        }
        
        $r = $params['r'];
        unset($params['r']);
        return Func::createUrl($r, $params);
    }


    /**
     * @param array $route
     * @param array $params
     * @return string
     * 全屋列表链接生成
     */
    public static function houseUrl($route, $param = [])
    {
        $default = [
            'type_id' => 0,
        	'style_id'=>0,
        	'acreage_id'=>0,
            'p' => 1,

        ];
    
		$params = array_merge($default, $param);
		if (!empty($param)) {
			foreach ($param as $k => $v) {
				$params[$k] = $v;
			}
		}
		 
		//var_dump($param);
        return Func::createUrl($route, $params);
    }

    /**
     * @param $src
     * @param $width_new
     * @param $height_new
     * @return string
     * 图片等比压缩
     */
    public static function imgResize($src, $width_new, $height_new, $quality = 95)
    {
        $cdn_base = Func::getImageCdnRand();
        $realsrc = Config::getParamsVal('UPLOAD_DIR').'public/'.$src;
        if(!file_exists($realsrc)){
            return false;
        }
        $src_tmp = pathinfo($src);
        $temp = pathinfo($realsrc);
        $name = $temp["filename"] . '_' . $width_new . '_' . $height_new . '_' . $quality;//文件基本名
        $dir = $temp["dirname"];//文件所在的文件夹
        $extension = isset($temp["extension"]) ? $temp["extension"] :'';//文件扩展名
        if ($extension ==''){
        	return false;
        }
        $savepath = "{$dir}/$name.$extension";//缩略图保存路径
        $returnpath = $cdn_base."{$src_tmp['dirname']}/$name.$extension";//返回CDN图片
        if (file_exists($savepath)) {
            return $returnpath;
        }
        //获取图片的基本信息
        $info = getimagesize($realsrc);
        $width = $info[0];//获取图片宽度
        $height = $info[1];//获取图片高度
        $w = $width_new;//压缩后图片的宽度
        $h = intval($width_new * $height / $width);//等比缩放图片高度 变整型

        $temp_img = imagecreatetruecolor($w, $h);//创建画布
        switch ($info[2]) {
            case 1:
                $im = imagecreatefromgif($realsrc);
                break;
            case 2:
                $im = imagecreatefromjpeg($realsrc);
                break;
            case 3:
                $im = imagecreatefrompng($realsrc);
                break;
        }
        imagecopyresampled($temp_img, $im, 0, 0, 0, 0, $w, $h, $width, $height);//将图片复制到画布中

        switch ($info[2]) {
            case 1:
                imagegif($temp_img, $savepath);
                break;
            case 2:
                imagejpeg($temp_img, $savepath, 100);
                break;
            case 3:
                imagepng($temp_img, $savepath, 100);
                break;
        }

        imagedestroy($im);
        return $returnpath;
    }
    /** 功能:
        * 此算法用于截取中文字符串
        * 函数以单个完整字符为单位进行截取,即一个英文字符和一个中文字符均表示一个单位长度
        * 参数:
        * 参数$string为要截取的字符串,
        * 参数$start为欲截取的起始位置,
        * 参数$length为要截取的字符个数(一个汉字或英文字符都算一个)
        * 返回值:
        * 返回截取结果字符串
        * */
    public static function  substr_cn($str, $start=0, $length, $charset="utf-8", $suffix=true)
    {
        if(function_exists("mb_substr"))
            $slice = mb_substr($str, $start, $length, $charset);
        elseif(function_exists('iconv_substr')) {
            $slice = iconv_substr($str,$start,$length,$charset);
            if(false === $slice) {
                $slice = '';
            }
        }else{
            $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
            $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
            $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
            $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
            preg_match_all($re[$charset], $str, $match);
            $slice = join("",array_slice($match[0], $start, $length));
        }
        return $suffix ? $slice.'...' : $slice;
    }

}
